﻿using System.Collections.Generic;
using System.Diagnostics;
using BackgroundQueueServiceSample.Controllers;
using BackgroundQueueServiceSample.Model;
using BackgroundQueueServiceSample.Views;
using BlueDot.Data.Core;
using BlueDot.Mobile.Core;

namespace BackgroundQueueServiceSample
{
    public class MainApplication : MobileApplication<MainShell>
    {
        #region Fields

        private string applicationName = "Main Application";

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the ScalperInternationalApplication class.
        /// </summary>
        public MainApplication()
        {
            Configuration = new InstantStartConfiguration();
        }

        #endregion

        #region Properties

        public override string Name
        {
            get { return applicationName; }
            set { applicationName = value; }
        }

        #endregion

        #region public

        public override void AddWorkflowDirector()
        {
            AddNew<MainWorkflowDirector, IWorkflowDirector>();
        }

        #endregion

        #region private

        private void LoadPeopleInBackground()
        {
            var workItem = new BackgroundQueueItem
                               {
                                   WorkDoneCallbackAddress = ApplicationActions.MainViewDataLoadDone
                               };

            workItem.Func = (() =>
                                 {
                                     // We are just doing a bunch of work to demontrate using 
                                     // the background queue service

                                     MainController.SetupDatabase();

                                     Trace.WriteLine("Selecting list of people");

                                     var people = (List<Person>) DataPersistence.Select<Person>();
                                     return new DataEventArgs<List<Person>>(people);
                                 });

            Actions[WellKnownActions.AddItemToBackgroundQueue].Fire(
                this,
                new DataEventArgs<BackgroundQueueItem>(workItem));
        }

        #endregion

        #region protected

        protected override void AddCustomServices()
        {
            // TODO: Uncomment the following two lines to enable the BackgroundQueueService
            // The BackgroundQueueService can be used to perform async data loading activities
            // on a separate thread that on completion, calls back to the UI thread using the 
            // action framework
            var backgroundLoaderService = AddNew<BackgroundQueueService>();
            backgroundLoaderService.Start();

            LoadPeopleInBackground();
        }

        #endregion
    }
}